package com.sirui.x.io.bio;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sirui.x.util.StreamUtils;

public class SocketClientWrapper {
	private static final Logger logger = LoggerFactory.getLogger(SocketClientWrapper.class);
	
	public void startAndSend() throws IOException {
		Socket client = new Socket("127.0.0.1", ServerSocketWrapper.LISTEN_PORT);
		try(OutputStream os = client.getOutputStream(); InputStream is = client.getInputStream()){
			String clientMsg = "Request URL: http://127.0.0.1/test\nRequest Method: POST\nContent-Type: application/json\nHost: 127.0.0.1\n{\"uname\":\"wahaha\"}";
			byte[] clientMsgBytes = Serializ.serialization(clientMsg);
			StreamUtils.copyMax4096(new ByteArrayInputStream(clientMsgBytes), os);
			logger.info("client send: {}", clientMsg);
			
			byte[] serverMsgBytes = StreamUtils.copyToByteArrayMax4096(is);
			String serverMsg = Serializ.deserialization(serverMsgBytes);
			logger.info("client recieve: {}", serverMsg);
		}catch (Exception e) {
			logger.error("", e);
		}finally {
			client.close();
		}
	}
}
